//
//  HJVideoView.m
//  project
//
//  Created by yefei on 2019/7/20.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJVideoView.h"
#import "HJVideoControllView.h"
#import "HJViewModel.h"
#import "HJVideoModel.h"
#import "AVPlayerManager.h"
#import "YFJourneyModel.h"

@interface HJVideoView ()<HJVideoControlViewDelegate,UIScrollViewDelegate,UIGestureRecognizerDelegate,HJVideoPlayerDelegate>
@property (nonatomic,strong) UIScrollView * scrollView;
/**
 上
 */
@property (nonatomic,strong) HJVideoControllView * topView;
/**
 中
 */
@property (nonatomic,strong) HJVideoControllView * ctrView;
/**
 下
 */
@property (nonatomic,strong) HJVideoControllView * btmView;

/**
 控制播放的索引，不完全等于当前播放内容的索引
 */
@property (nonatomic, assign) NSInteger index;
/**
 当前播放内容是h索引
 */
@property (nonatomic, assign) NSInteger currentPlayIndex;
/**
 当前VC
 */
@property (nonatomic, weak) UIViewController *vc;
@property (nonatomic, assign) BOOL isPushed;
/**
 视频数据源
 */
@property (nonatomic,strong) NSMutableArray <HJVideoModel *>* videos;
/**
记录滑动前的播放状态
 */
@property (nonatomic, assign) BOOL isPlaying_beforeScroll;
/**
 刷新更多
 */
@property (nonatomic, assign) BOOL isRefreshMore;
@property (nonatomic, strong) UIPanGestureRecognizer *panGesture;
/**
 开始移动时的位置
 */
@property (nonatomic, assign) CGFloat startLocationY;
/**
 记录播放内容ID
 */
@property (nonatomic, copy) NSString *currentPlayId;
/**
 播放层
 */
@property (nonatomic, strong) HJVideoPlayer *player;

@end

@implementation HJVideoView

- (instancetype)initWithVC:(UIViewController *)vc isPushed:(BOOL)isPushed {
    if (self = [super init]) {
        self.vc = vc;
        self.isPushed = isPushed;
        // 关注点击 编辑数据 更改UI 关注按钮显示与隐藏
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(attentionNoti:) name:NotificationAttention object:nil];
        
        [self addSubview:self.scrollView];
        [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self);
            CGFloat inset_H = isPushed ? 0 : Height_TabBar;
            make.bottom.equalTo(self).inset(inset_H);
        }];
#warning 不是Push 过来的添加上拉加载
        if (!isPushed) {
            self.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                [self.viewModel refreshNewListWithSuccess:^(NSArray * _Nonnull list) {
                    // 暂停播放
                    [self.player pausePlay];
                    [self setModels:list index:0];
                    [self.scrollView.mj_header endRefreshing];
                    self.isRefreshMore = NO;
                } failure:^(NSString * _Nonnull error) {
                    self.isRefreshMore = NO;
                }];
            }];
            self.scrollView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                // 暂停播放
                [self.player pausePlay];
                // 当播放索引为最后一个时才会触发下拉刷新
                self.currentPlayIndex = self.videos.count - 1;
                [self.viewModel refreshMoreListWithSuccess:^(NSArray * _Nonnull list) {
                    self.isRefreshMore = NO;
                    if (list) {
                        if (self.videos.count == 0) {
                            [self setModels:list index:0];
                        }else {
                            [self resetModels:list];
                        }
                        [self.scrollView.mj_footer endRefreshing];
                    }else {
                        [self.scrollView.mj_footer endRefreshingWithNoMoreData];
                    }
                } failure:^(NSString * _Nonnull error) {
                    self.isRefreshMore = NO;
                    [self.scrollView.mj_footer endRefreshingWithNoMoreData];
                }];
            }];
            [self.scrollView addGestureRecognizer:self.panGesture];
        }
    }
    return self;
}

/**
 获取滚动的contentHeight
 @return 高度
 */
-(CGFloat)scrollContentHeight {
    CGFloat height = 0.0;
    if (self.isPushed) {
        height = SCREEN_HEIGTH;
    }else {
        height = SCREEN_HEIGTH - Height_TabBar;
    }
    return height;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat controlW = CGRectGetWidth(self.scrollView.frame);
    CGFloat controlH = CGRectGetHeight(self.scrollView.frame);
    
    self.topView.frame = CGRectMake(0, 0, controlW, controlH);
    self.ctrView.frame = CGRectMake(0, controlH, controlW, controlH);
    self.btmView.frame = CGRectMake(0, 2 * controlH, controlW, controlH);
}
#pragma mark - Public Methods
- (void)setModels:(NSArray *)models index:(NSInteger)index {
    [self.videos removeAllObjects];
    [self.videos addObjectsFromArray:models];
    
    self.index = index;
    self.currentPlayIndex = index;
    
    if (models.count == 0) return;
    if (models.count == 1) {
        [self.ctrView removeFromSuperview];
        [self.btmView removeFromSuperview];
        
        self.scrollView.contentSize = CGSizeMake(0, [self scrollContentHeight]);
        self.topView.hidden = NO;
        self.topView.model = self.videos.firstObject;
        [self playVideoFrom:self.topView];
    }else if (models.count == 2) {
        [self.btmView removeFromSuperview];
        
        self.scrollView.contentSize = CGSizeMake(0, [self scrollContentHeight] * 2);
        self.topView.hidden = NO;
        self.ctrView.hidden = NO;
        self.topView.model  = self.videos.firstObject;
        self.ctrView.model  = self.videos.lastObject;
        if (index == 1) {
            self.scrollView.contentOffset = CGPointMake(0, [self scrollContentHeight]);
            [self playVideoFrom:self.ctrView];
        }else {
            [self playVideoFrom:self.topView];
        }
    }else {
        self.topView.hidden = NO;
        self.ctrView.hidden = NO;
        self.btmView.hidden = NO;
        if (index == 0) { // 如果是第一个，则显示上视图，且预加载中下视图
            self.topView.model = self.videos[index];
            self.ctrView.model = self.videos[index + 1];
            self.btmView.model = self.videos[index + 2];
            // 播放第一个
            [self playVideoFrom:self.topView];
        }else if (index == models.count - 1) { // 如果是最后一个，则显示最后视图，且预加载前两个
            self.btmView.model = self.videos[index];
            self.ctrView.model = self.videos[index - 1];
            self.topView.model = self.videos[index - 2];
            // 显示最后一个
            self.scrollView.contentOffset = CGPointMake(0, ([self scrollContentHeight]) * 2);
            // 播放最后一个
            [self playVideoFrom:self.btmView];
        }else { // 显示中间，播放中间，预加载上下
            self.ctrView.model = self.videos[index];
            self.topView.model = self.videos[index - 1];
            self.btmView.model = self.videos[index + 1];
            // 显示中间
            self.scrollView.contentOffset = CGPointMake(0, [self scrollContentHeight]);
            // 播放中间
            [self playVideoFrom:self.ctrView];
        }
    }
}

- (void)resetModels:(NSArray *)models {
    [self.videos addObjectsFromArray:models];
}

- (void)pause {
    self.isPlaying_beforeScroll = self.player.isPlaying;
    [self.player pausePlay];
}

- (void)resume {
    if (self.isPlaying_beforeScroll) {
        [self.player resumePlay];
    }
}

- (void)destoryPlayer {
    self.scrollView.delegate = nil;
    [self.player removeVideo];
}

#pragma mark - 应该滑动到哪个播放界面
- (void)playVideoFrom:(HJVideoControllView *)fromView {
    //移除原来的播放
    [self.player removeVideo];
    // 取消原来视图的代理
    self.currentPlayView.delegate = nil;
    
    // 切换播放视图
    self.currentPlayId = fromView.model.albumId;
    self.currentPlayView  = fromView;
    self.currentPlayIndex = [self indexOfModel:fromView.model];
    LKLog(@"当前播放索引====%zd", self.currentPlayIndex);
    // 设置新视图的代理
    self.currentPlayView.delegate = self;
    // 重新播放
    @weakify(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        @strongify(self);
        [self.player playVideoWithView:fromView.coverImgView url:fromView.model.videoSource.url];
    });
}
// 获取当前播放内容的索引
- (NSInteger)indexOfModel:(HJVideoModel *)model {
    __block NSInteger index = 0;
    [self.videos enumerateObjectsUsingBlock:^(HJVideoModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([model.albumId isEqualToString:obj.albumId]) {
            index = idx;
        }
    }];
    return index;
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.currentPlayIndex == 0 && scrollView.contentOffset.y < 0) {
        self.scrollView.contentOffset = CGPointZero;
    }
    // slier处理
    if (scrollView.contentOffset.y == 0 || scrollView.contentOffset.y == [self scrollContentHeight] || scrollView.contentOffset.y == 2 * ([self scrollContentHeight])) {
        if ([self.delegate respondsToSelector:@selector(videoView:didScrollIsCritical:)]) {
            [self.delegate videoView:self didScrollIsCritical:YES];
        }
    }else {
        if ([self.delegate respondsToSelector:@selector(videoView:didScrollIsCritical:)]) {
            [self.delegate videoView:self didScrollIsCritical:NO];
        }
    }
    
    // 小于等于三个，不用处理
    if (self.videos.count <= 3) return;
    // 上滑到第一个
    if (self.index == 0 && scrollView.contentOffset.y <= [self scrollContentHeight]) return;
    // 下滑到最后一个
    if (self.index > 0 && self.index == self.videos.count - 1 && scrollView.contentOffset.y > [self scrollContentHeight]) return;
    // 判断是从中间视图上滑还是下滑
    if (scrollView.contentOffset.y >= 2 * [self scrollContentHeight]) {  // 上滑
        [self.player removeVideo];  // 在这里移除播放，解决闪动的bug
        if (self.index == 0) {
            self.index += 2;
            scrollView.contentOffset = CGPointMake(0, [self scrollContentHeight]);
            self.topView.model = self.ctrView.model;
            self.ctrView.model = self.btmView.model;
            
        }else {
            self.index += 1;
            if (self.index == self.videos.count - 1) {
                self.ctrView.model = self.videos[self.index - 1];
            }else {
                scrollView.contentOffset = CGPointMake(0, [self scrollContentHeight]);
                
                self.topView.model = self.ctrView.model;
                self.ctrView.model = self.btmView.model;
            }
        }
        if (self.index < self.videos.count - 1 && self.videos.count >= 3) {
            self.btmView.model = self.videos[self.index + 1];
        }
    }else if (scrollView.contentOffset.y <= 0) { // 下滑
        [self.player removeVideo];  // 在这里移除播放，解决闪动的bug
        if (self.index == 1) {
            self.topView.model = self.videos[self.index - 1];
            self.ctrView.model = self.videos[self.index];
            self.btmView.model = self.videos[self.index + 1];
            self.index -= 1;
        }else {
            if (self.index == self.videos.count - 1) {
                self.index -= 2;
            }else {
                self.index -= 1;
            }
            scrollView.contentOffset = CGPointMake(0, [self scrollContentHeight]);
            
            self.btmView.model = self.ctrView.model;
            self.ctrView.model = self.topView.model;
            
            if (self.index > 0) {
                self.topView.model = self.videos[self.index - 1];
            }
        }
    }
    
    if (self.isPushed) return;
    // 自动刷新，如果想要去掉自动刷新功能，去掉下面代码即可
    if (scrollView.contentOffset.y == [self scrollContentHeight]) {
        if (self.isRefreshMore) return;
        // 播放到倒数第二个时，请求更多内容
        if (self.currentPlayIndex == self.videos.count - 3) {
            self.isRefreshMore = YES;
            [self refreshMore];
        }
    }
    if (scrollView.contentOffset.y == 2 * [self scrollContentHeight]) {
        [self refreshMore];
    }
}

// 结束滚动后开始播放
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y == 0) {
        if (self.currentPlayId == self.topView.model.albumId) return;
        [self playVideoFrom:self.topView];
    }else if (scrollView.contentOffset.y == [self scrollContentHeight]) {
        if (self.currentPlayId == self.ctrView.model.albumId) return;
        [self playVideoFrom:self.ctrView];
    }else if (scrollView.contentOffset.y == 2 * [self scrollContentHeight]) {
        if (self.currentPlayId == self.btmView.model.albumId) return;
        [self playVideoFrom:self.btmView];
    }
}
#pragma mark-- 刷新更多
- (void)refreshMore {
    [self.viewModel refreshMoreListWithSuccess:^(NSArray * _Nonnull list) {
        self.isRefreshMore = NO;
        if (list) {
            [self.videos addObjectsFromArray:list];
            [self.scrollView.mj_footer endRefreshing];
        }else {
            [self.scrollView.mj_footer endRefreshingWithNoMoreData];
        }
    } failure:^(NSString * _Nonnull error) {
        self.isRefreshMore = NO;
        [self.scrollView.mj_footer endRefreshingWithNoMoreData];
    }];
}

#pragma mark - Gesture
- (void)handlePanGesture:(UIPanGestureRecognizer *)panGesture {
    if (self.currentPlayIndex == 0) {
        CGPoint location = [panGesture locationInView:panGesture.view];
        switch (panGesture.state) {
            case UIGestureRecognizerStateBegan: {
                self.startLocationY = location.y;
            }
                break;
            case UIGestureRecognizerStateChanged: {
                // 这里取整是解决上滑时可能出现的distance > 0的情况
                CGFloat distance = ceil(location.y) - ceil(self.startLocationY);
                if (distance > 0) { // 只要distance>0且没松手 就认为是下滑
                    self.scrollView.panGestureRecognizer.enabled = NO;
                }
//                if (self.scrollView.panGestureRecognizer.enabled == NO) {
//                    if ([self.delegate respondsToSelector:@selector(videoView:didPanWithDistance:isEnd:)]) {
//                        [self.delegate videoView:self didPanWithDistance:distance isEnd:NO];
//                    }
//                }
            }
                break;
            case UIGestureRecognizerStateFailed:
            case UIGestureRecognizerStateCancelled:
            case UIGestureRecognizerStateEnded: {
                if (self.scrollView.panGestureRecognizer.enabled == NO) {
//                    CGFloat distance = location.y - self.startLocationY;
//                    if ([self.delegate respondsToSelector:@selector(videoView:didPanWithDistance:isEnd:)]) {
//                        [self.delegate videoView:self didPanWithDistance:distance isEnd:YES];
//                    }
                    self.scrollView.panGestureRecognizer.enabled = YES;
                }
            }
                break;
            default:
                break;
        }
        [panGesture setTranslation:CGPointZero inView:panGesture.view];
    }
}

// 允许多个手势响应
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}
#pragma mark --懒加载ViewModel
-(HJViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [HJViewModel new];
    }
    return _viewModel;
}

#pragma mark --加载视图UI和控件
-(UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [UIScrollView new];
        _scrollView.pagingEnabled = YES;
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.clipsToBounds = YES;
        _scrollView.delegate = self;
        
        [_scrollView addSubview:self.topView];
        [_scrollView addSubview:self.ctrView];
        [_scrollView addSubview:self.btmView];
        _scrollView.contentSize = CGSizeMake(0, [self scrollContentHeight] * 3);
        if (@available(iOS 11.0, *)) {
            _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _scrollView;
}

-(HJVideoControllView *)topView {
    if (!_topView) {
        _topView = [HJVideoControllView new];
        _topView.hidden = YES;
    }
    return _topView;
}

-(HJVideoControllView *)ctrView {
    if (!_ctrView) {
        _ctrView = [HJVideoControllView new];
        _ctrView.hidden = YES;
    }
    return _ctrView;
}

-(HJVideoControllView *)btmView {
    if (!_btmView) {
        _btmView = [HJVideoControllView new];
        _btmView.hidden = YES;
    }
    return _btmView;
}

-(NSMutableArray <HJVideoModel *>*)videos {
    if (!_videos) {
        _videos = [NSMutableArray array];
    }
    return _videos;
}

- (UIPanGestureRecognizer *)panGesture {
    if (!_panGesture) {
        _panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
        _panGesture.delegate = self;
    }
    return _panGesture;
}


-(HJVideoPlayer *)player {
    if (!_player) {
        _player = [HJVideoPlayer new];
        _player.delegate = self;
    }
    return _player;
}

#pragma mark--HJVideoPlayerDelegate 播放代理
- (void)player:(HJVideoPlayer *)player statusChanged:(HJVideoPlayerStatus)status {
    switch (status) {
        case HJVideoPlayerStatusUnload:   // 未加载
            break;
        case HJVideoPlayerStatusPrepared:   // 准备播放
            [self.currentPlayView startLoading];
            break;
        case HJVideoPlayerStatusLoading: // 加载中
        {
            [self.currentPlayView hidePlayBtn];
        }
            break;
        case HJVideoPlayerStatusPlaying:// 播放中
        {
            [self.currentPlayView hidePlayBtn];
            [self.currentPlayView stopLoading];
        }
            break;
        case HJVideoPlayerStatusPaused: // 暂停
        {
            [self.currentPlayView stopLoading];
            [self.currentPlayView showPlayBtn];
        }
            break;
        case HJVideoPlayerStatusEnded:// 播放结束
        {
            // 重新开始播放
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.player resetPlay];
            });
        }
            break;
        case HJVideoPlayerStatusError: // 错误
            break;
        default:
            break;
    }
}

-(void)player:(HJVideoPlayer *)player currentTime:(float)currentTime totalTime:(float)totalTime progress:(float)progress {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.currentPlayView setProgress:progress];
    });
}

#pragma mark -- HJVideoControlViewDelegate 自定义视图点击事件代理
-(void)controlViewDidClickSelf:(HJVideoControllView *)controlView {
    if (self.player.isPlaying) {
        [self.player pausePlay];
    }else {
        [self.player resumePlay];
    }
}

- (void)controlView:(HJVideoControllView *)controlView touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//    [controlView showLikeAnimation];
}
// 头像
- (void)controlViewDidClickIcon:(HJVideoControllView *)controlView {
    if ([self.delegate respondsToSelector:@selector(videoView:didClickIcon:)]) {
        [self.delegate videoView:self didClickIcon:controlView.model];
    }
}
// 评论
- (void)controlViewDidClickComment:(HJVideoControllView *)controlView {
    if ([self.delegate respondsToSelector:@selector(videoView:didClickComment:)]) {
        [self.delegate videoView:self didClickComment:controlView.model];
    }
}
// 分享
- (void)controlViewDidClickShare:(HJVideoControllView *)controlView {
    if ([self.delegate respondsToSelector:@selector(videoView:didClickShare:)]) {
        [self.delegate videoView:self didClickShare:controlView.model];
    }
}

#pragma mark -- 点击关注后 遍历数据 更改模型
-(void)controlViewDidClickAttention:(HJVideoControllView *)controlView videoModel:(HJVideoModel *)videoModel {
    [self changeModelConcernWithUserId:videoModel.user.userId concern:YES];
}
-(void)attentionNoti:(NSNotification *)noti {
    if ([noti.userInfo.allKeys containsObject:@"userId"]) {
        BOOL concern = [noti.userInfo[@"concern"] boolValue];
        [self changeModelConcernWithUserId:noti.userInfo[@"userId"] concern:concern];
        [self.currentPlayView setConcern:concern];
    }
}

-(void)changeModelConcernWithUserId:(NSString *)userId concern:(BOOL)concern {
    NSMutableArray <HJVideoModel *>* arr = [NSMutableArray arrayWithCapacity:self.videos.count];
    for (HJVideoModel * model in self.videos) {
        if ([userId isEqualToString:model.user.userId]) {
            model.concern = concern;
        }
        [arr addObject:model];
    }
    self.videos = [NSMutableArray arrayWithArray:arr];
    if ([self.topView.model.user.userId isEqualToString:userId]) {
        [self.topView setConcern:concern];
    }else if ([self.btmView.model.user.userId isEqualToString:userId]) {
        [self.btmView setConcern:concern];
    }else if ([self.ctrView.model.user.userId isEqualToString:userId]) {
        [self.ctrView setConcern:concern];
    }
}



@end
